package com.zby.business.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zby.business.R;
import com.zby.business.activity.Commodity;
import com.zby.business.adapter.SearchListViewAdapter;
import com.zby.business.db.MyDatabaseHelper;
import com.zby.business.util.Util;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by BY on 2015/12/28.
 */
public class SearchFragment extends Fragment {
    private View view;
    private ImageView backImage, deleteImage;
    private TextView searchText, sweepRecordTextView;
    private EditText searchEdit;
    private ListView searchListView;
    private InputMethodManager imm;
    private SQLiteDatabase db;
    private ArrayList searchRecord;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.search_fragment, null);
        initView();
        initData();
        return view;
    }

    private void initData() {
        Cursor cursor = db.query("search_record", null, null, null, null, null, "search_record_id desc");
        if (cursor.moveToFirst()) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                searchRecord.add(cursor.getString(cursor.getColumnIndex("record")));
            }
        } else {
            LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.searchRecordLinearLayout);
            linearLayout.setVisibility(View.GONE);
        }
        cursor.close();
        SearchListViewAdapter searchListViewAdapter = new SearchListViewAdapter(searchRecord, getContext());
        searchListView.setAdapter(searchListViewAdapter);
    }

    private void showAlert(String message, final String SQL) {
        AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
        alert.setMessage(message);
        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                db.execSQL(SQL);
                searchRecord.clear();
                initData();
            }
        });
        alert.setNegativeButton("取消", null);
        alert.show();
    }

    private void initView() {
        MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(getContext(), "graduate.db");
        db = myDatabaseHelper.getReadableDatabase();
        searchListView = (ListView) view.findViewById(R.id.searchListView);
        searchEdit = (EditText) view.findViewById(R.id.searchEdit);
        backImage = (ImageView) view.findViewById(R.id.searchBack);
        deleteImage = (ImageView) view.findViewById(R.id.deleteSearch);
        searchRecord = new ArrayList<>();
        searchText = (TextView) view.findViewById(R.id.searchText);
        sweepRecordTextView = (TextView) view.findViewById(R.id.sweepRecordTextView);
        searchEdit.setFocusable(true);
        searchEdit.setFocusableInTouchMode(true);
        searchEdit.requestFocus();
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, 0);
        searchText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String searchContent = searchEdit.getText().toString().trim();
                if (!searchContent.equals("")) {
                    Cursor cursor = db.query("search_record", null, "record=?", new String[]{searchContent}, null, null, null);
                    if (cursor.moveToFirst()) {
                        db.delete("search_record", "record=?", new String[]{searchContent});
                        db.execSQL("insert into search_record(record) values(?)", new String[]{searchContent});
                    } else {
                        db.execSQL("insert into search_record(record) values(?)", new String[]{searchContent});
                    }
                    cursor.close();
                    Intent intent = new Intent(getActivity(), Commodity.class);
                    intent.putExtra("name", searchEdit.getText().toString());
                    startActivity(intent);
                }
            }
        });
        sweepRecordTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlert("确定要清除记录？", "delete from search_record");
            }
        });
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(searchEdit.getWindowToken(), 0);
                }
                getFragmentManager().popBackStack();
            }
        });
        deleteImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEdit.setText("");
            }
        });
        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                searchEdit.setText(searchRecord.get(position) + "");
                Intent intent = new Intent(getActivity(), Commodity.class);
                intent.putExtra("name", searchRecord.get(position) + "");
                startActivity(intent);
            }
        });
        searchListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showAlert("删除该条记录？", "delete from search_record where record = '" + searchRecord.get(position) + "'");
                return true;
            }
        });
    }
}
